package eu.boss.activities;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import Util.FinishListener;
import Util.Util;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import eu.boss.R;
import eu.boss.controller.ShadowStatsController;
import eu.boss.exceptions.LoginException;
import eu.boss.exceptions.ServerErrorException;
import eu.boss.http.Http;
import eu.boss.model.LoginResponseMessage;
/**
 * Splashcreen. If an account is saved, the login is made automatically and FragmentSliderActivity is loaded.
 * Otherwise, loads LoginActivity
 * @author Arnaud
 *
 */
public class SplashScreenActivity extends Activity {


	private ShadowStatsController mController;
	private SharedPreferences sharedPreferences;
	private String hash;
	private ServiceConnection mControllerConnection = new ServiceConnection() {
		// Called when the connection with the service is established
		public void onServiceConnected(ComponentName className, IBinder service) {
			mController = ((ShadowStatsController.LocalBinder) service)
					.getService();
			if (Util.isOnline(SplashScreenActivity.this))
			{
				sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE);
				hash = sharedPreferences.getString("hash", null);
				if (hash!=null){		
					mController.setHash(hash);
					UserLoginTask ut = new UserLoginTask();
					ut.execute();					
				}
				else{
					finish();
					startActivity(new Intent(SplashScreenActivity.this, LoginActivity.class));
				}
			}
			else
				displayErrorMessageAndFinish(getString(R.string.connection_error));	
					
		}

		// Called when the connection with the service disconnects unexpectedly
		public void onServiceDisconnected(ComponentName className) {
			mController = null;
		}
	};
	
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splashscreen);
	}
	
	
	@Override
	public void onStart() {
		super.onStart();
		// new intent to bind service
		Intent intent = new Intent(this, ShadowStatsController.class);
		this.bindService(intent, mControllerConnection, Context.BIND_AUTO_CREATE);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		unbindService(mControllerConnection);
	}

	/**
	 * AsyncTask making HTTP post request in a second thread. Login and getting statsList
	 * 
	 * @author Arnaud
	 * 
	 */
	private class UserLoginTask extends AsyncTask<Void, Void, LoginResponseMessage> {

		String error = null;
		
		@Override
		protected LoginResponseMessage doInBackground(Void... params) {

			ObjectMapper jacksonMapper = new ObjectMapper();
			LoginResponseMessage loginResponse = null;
			String url = getString(R.string.web_app_url) + getString(R.string.login_url);
			String response = null;
			Http request = new Http();

			try {
				// Creation of a pair Key/Value to put on the server and get
				// response.
				ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
				pairs.add(new BasicNameValuePair("hash", hash));
				response = request.executePostRequest(url, pairs, hash);
				if (response.compareTo("LOGIN ERROR")==0)
					throw new LoginException(SplashScreenActivity.this);
				
				loginResponse = jacksonMapper.readValue(response, LoginResponseMessage.class);
				

			} catch (JsonParseException e) {				
				error=e.getMessage();				
			} catch (JsonMappingException e) {
				error=e.getMessage();
			} catch (ClientProtocolException e) {
				error = e.getMessage();
			} catch (ServerErrorException e) {
				error = e.getMessage();
			} catch (IOException e) {
				error = e.getMessage();
			} catch (LoginException e) {
				error = e.getMessage();
			}

			return loginResponse;
		}

		@Override
		protected void onPostExecute(LoginResponseMessage result) {
			super.onPostExecute(result);
			if (error == null) {	
				mController.setTeamList(result.getTeamList());
				mController.setPlayersList(result.getPlayerList());
				finish();
				startActivity(new Intent(SplashScreenActivity.this, FragmentsSliderActivity.class));
			} else {
				displayErrorMessageAndFinish(error);
			}
		};

	}

	/**
	 * Displaying error message in an AlertDialog and exit activity
	 * 
	 * @param msg
	 *            message to display
	 */
	public void displayErrorMessageAndFinish(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.error));
		builder.setMessage(msg);
		builder.setPositiveButton(R.string.ok, new FinishListener(this));
		builder.show();
	}
}
